package com.huicoo.forestmanager.ui.media;

import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huicoo.forestmanager.R;
import com.huicoo.forestmanager.others.MediaEvent;
import com.huicoo.forestmanager.util.AttachmentHelper;
import com.huicoo.forestmanager.util.LogUtils;

import org.greenrobot.eventbus.EventBus;

public class CaptureVideoActivity extends AppCompatActivity implements SurfaceHolder.Callback, Camera.AutoFocusCallback {
    String TAG = "CaptureVideoActivity";
    private SurfaceView mSurfaceView;
    private RelativeLayout rl_shot;
    private ImageView iv_status;
    private TextView tv_seconds, tv_status;
    private boolean mIsRecord = false; //是否正在录像
    private Camera mCamera;
    private MediaRecorder mMediaRecorder;
    private String mMediaPath;
    private MediaPlayer mMediaPlayer;
    private SurfaceHolder mSurfaceHolder;

    private int second;
    private long startTime;
    private long endTime;

    private boolean captureDone = false;

    private Handler mHandler = new Handler();
    private Runnable mUpdateStatusTimer = new Runnable() {
        public void run() {
            second--;
            tv_seconds.setText(String.format("剩余%s''", String.valueOf(second)));
            LogUtils.v("gogogo second = " + second);
            if (second == 0) {
                stopRecord();
                mHandler.removeCallbacksAndMessages(null);
            } else {
                mHandler.postDelayed(this, 1000);
            }
        }
    };

    private void runSeconds() {
        second = 11;
        mHandler.removeCallbacksAndMessages(null);
        mHandler.post(mUpdateStatusTimer);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_capture_video);

        mSurfaceView = findViewById(R.id.surfaceview);
        mSurfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); // 必须-设置Surface不需要维护自己的缓冲区
        mSurfaceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //自动对焦 并回调
                if (mCamera != null) {
                    mCamera.autoFocus(CaptureVideoActivity.this);
                }
            }
        });

        rl_shot = findViewById(R.id.rl_shot);
        iv_status = findViewById(R.id.iv_status);
        tv_seconds = findViewById(R.id.tv_seconds);
        tv_status = findViewById(R.id.tv_status);

        SurfaceHolder holder = mSurfaceView.getHolder();
        holder.addCallback(this);

        initBtnClick();
    }

    private void initBtnClick() {
        rl_shot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mIsRecord) {
                    Log.d(TAG, "首次点击开始录像 ");
                    if (prepareVideoRecorder()) {
//                        try {
                        mMediaRecorder.start();
//                        } catch (IllegalStateException e) {
//                            e.printStackTrace();
//                        } catch (RuntimeException e) {
//                            e.printStackTrace();
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
                        /* 获取开始时间* */
                        startTime = System.currentTimeMillis();
                        runSeconds();
                        mIsRecord = true;
                        iv_status.setImageResource(R.drawable.shape_circle_red);
                        tv_seconds.setVisibility(View.VISIBLE);
                        tv_status.setText("点击停止录像");
                    }
                } else {
                    Log.d(TAG, "再次点击停止录像");
                    stopRecord();
                }
            }
        });

//        mPlayBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (mMediaPlayer == null) {
//                    mMediaPlayer = new MediaPlayer();
//                }
//                mMediaPlayer.reset();
//                Uri uri = Uri.parse(mMediaPath);
//                mMediaPlayer = MediaPlayer.create(CaptureVideoActivity.this, uri);
//                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//                mMediaPlayer.setDisplay(mSurfaceHolder);
//                try {
//                    mMediaPlayer.prepare();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                mMediaPlayer.start();
//            }
//        });

    }

    private void stopRecord() {
        try {
            mMediaRecorder.stop();
            /* 获取结束时间* */
            endTime = System.currentTimeMillis();
            releaseMediaRecorder();
            mCamera.lock();
            iv_status.setImageResource(R.drawable.shape_circle_white);
            tv_seconds.setVisibility(View.GONE);
            tv_status.setText("点击开始录像");
            mIsRecord = false;
            mHandler.removeCallbacksAndMessages(null);

            if (mCamera != null) {
                mCamera.release();
                mCamera = null;
            }

            EventBus.getDefault().post(new MediaEvent(3, mMediaPath, (int) ((endTime - startTime) / 1000)));
            captureDone = true;
            finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 相机预览前的准备工作代码 单独抽出来
     * */
    private boolean prepareVideoRecorder() {
        try {
            /*camera相关设置部分*/
            if (mCamera != null) {
                mCamera.unlock();
            }
            if (mMediaRecorder == null) {
                mMediaRecorder = new MediaRecorder();
            }
            mMediaRecorder.reset();
            mMediaRecorder.setMaxDuration(15000);
            mMediaRecorder.setCamera(mCamera);
            /*recorder设置部分*/
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

            mMediaRecorder.setOrientationHint(90);
            mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_480P));
            mMediaRecorder.setOutputFile(getOutputMediaFile());
            mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
            mMediaRecorder.prepare();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /*
     *创建视频存储文件夹 录制好的视频存储在手机外部存储中 以录像时间+mp4格式命名
     * */
    private String getOutputMediaFile() {
        Log.d(TAG, "获取视频存储的位置 ");
        return mMediaPath = AttachmentHelper.getFilePath(System.currentTimeMillis() + ".mp4");
    }

    /*
     * 录制视频结束时释放相机资源
     * */
    private void releaseMediaRecorder() {
        Log.d(TAG, "录制结束后释放资源 ");
        if (mMediaRecorder != null) {
            mMediaRecorder.reset();   // clear recorder configuration
            mMediaRecorder.release(); // release the recorder object
            mMediaRecorder = null;
            mCamera.lock();           // lock camera for later use
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        LogUtils.v("gogogo surface create ");
        mSurfaceHolder = surfaceHolder;

        if (mCamera == null) {
            mCamera = Camera.open(0);//Camera.CameraInfo.CAMERA_FACING_BACK
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        LogUtils.v("gogogo surface changed ");
        mSurfaceHolder = surfaceHolder;

        try {
            mCamera.setPreviewDisplay(surfaceHolder);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置旋转角度
        mCamera.setDisplayOrientation(90);
        mCamera.startPreview();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        mSurfaceView = null;
        mSurfaceHolder = null;
        releaseMediaRecorder();

        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    @Override
    public void onAutoFocus(boolean success, Camera camera) {
        Log.v(TAG, "gogogo on auto focus = " + success);
    }

    @Override
    protected void onDestroy() {
        if (!captureDone) {
            EventBus.getDefault().post(new MediaEvent(3, null));
        }
        if (mMediaRecorder != null) {
            mMediaRecorder.stop();
        }
        releaseMediaRecorder();
        mIsRecord = false;
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }

        if (mCamera != null) {
            mCamera.release();
            mCamera = null;
        }
        super.onDestroy();
    }
}
